<template>
  <div class="wms-item-category-page art-full-height">
    <!-- 搜索栏 -->
    <WmsItemCategorySearch
      v-model:filter="searchFilter"
      @search="handleSearch"
      @reset="handleReset"
    />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格工具栏 -->
      <ArtTableHeader
        v-model:columns="columnChecks"
        @refresh="refreshData"
        layout="refresh,size,fullscreen,columns,settings"
      >
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple>
            <ElIcon><Plus /></ElIcon>
            新增分类
          </ElButton>
          <ElButton @click="handleExpandAll" v-ripple>
            <ElIcon><Expand /></ElIcon>
            展开全部
          </ElButton>
          <ElButton @click="handleCollapseAll" v-ripple>
            <ElIcon><Fold /></ElIcon>
            收起全部
          </ElButton>
        </template>
      </ArtTableHeader>

      <!-- 树形表格 -->
      <ElTable
        ref="tableRef"
        v-loading="isLoading"
        :data="treeData"
        row-key="id"
        :tree-props="{ children: 'children' }"
        :default-expand-all="false"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <ElTableColumn type="selection" width="50" />
        <ElTableColumn
          prop="categoryName"
          label="分类名称"
          min-width="200"
          show-overflow-tooltip
        />
        <ElTableColumn
          prop="categoryCode"
          label="分类编码"
          width="150"
          show-overflow-tooltip
        />
        <ElTableColumn prop="orderNum" label="排序" width="80" align="center" />
        <ElTableColumn prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <ElTag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? "正常" : "停用" }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn
          prop="createTime"
          label="创建时间"
          width="180"
          align="center"
        />
        <ElTableColumn label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <ElButton type="primary" link @click="showDialog('add', row)">
              <ElIcon><Plus /></ElIcon>
              新增子类
            </ElButton>
            <ElButton type="primary" link @click="showDialog('edit', row)">
              <ElIcon><Edit /></ElIcon>
              编辑
            </ElButton>
            <ElButton type="danger" link @click="handleDelete(row)">
              <ElIcon><Delete /></ElIcon>
              删除
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>

    <!-- 分类弹窗 -->
    <WmsItemCategoryDialog
      v-model:visible="dialogVisible"
      :type="dialogType"
      :category-data="currentCategoryData"
      :parent-data="parentCategoryData"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { WmsItemCategoryService } from "@/api/wms/basicApi";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Expand, Fold } from "@element-plus/icons-vue";

// 导入子组件
import WmsItemCategorySearch from "./components/WmsItemCategorySearch.vue";
import WmsItemCategoryDialog from "./components/WmsItemCategoryDialog.vue";

defineOptions({ name: "WmsItemCategory" });

// 表格引用
const tableRef = ref();

// 数据状态
const isLoading = ref(false);
const treeData = ref<WMS.Basic.ItemCategoryTreeInfo[]>([]);
const selectedRows = ref<WMS.Basic.ItemCategoryInfo[]>([]);

// 搜索状态
const searchFilter = reactive({
  categoryName: "",
  categoryCode: "",
  status: undefined,
});

// 弹窗状态
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const currentCategoryData = ref<WMS.Basic.ItemCategoryInfo | null>(null);
const parentCategoryData = ref<WMS.Basic.ItemCategoryInfo | null>(null);

// 列显示控制
const columnChecks = ref({
  categoryName: true,
  categoryCode: true,
  orderNum: true,
  status: true,
  createTime: true,
});

// 获取树形数据
const fetchTreeData = async () => {
  try {
    isLoading.value = true;
    const response =
      await WmsItemCategoryService.getItemCategoryTree(searchFilter);
    treeData.value = response.data || [];
  } catch (error) {
    ElMessage.error("获取分类数据失败");
    console.error("Error fetching tree data:", error);
  } finally {
    isLoading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  fetchTreeData();
};

// 重置处理
const handleReset = () => {
  Object.keys(searchFilter).forEach((key) => {
    searchFilter[key] = key === "status" ? undefined : "";
  });
  fetchTreeData();
};

// 刷新数据
const refreshData = () => {
  fetchTreeData();
};

// 展开全部
const handleExpandAll = () => {
  // TODO: 实现展开全部逻辑
  ElMessage.info("展开全部功能开发中");
};

// 收起全部
const handleCollapseAll = () => {
  // TODO: 实现收起全部逻辑
  ElMessage.info("收起全部功能开发中");
};

// 选择变化处理
const handleSelectionChange = (selection: WMS.Basic.ItemCategoryInfo[]) => {
  selectedRows.value = selection;
};

// 显示弹窗
const showDialog = (
  type: "add" | "edit",
  data?: WMS.Basic.ItemCategoryInfo,
) => {
  dialogType.value = type;
  if (type === "edit") {
    currentCategoryData.value = { ...data! };
    parentCategoryData.value = null;
  } else {
    currentCategoryData.value = null;
    parentCategoryData.value = data || null; // 如果有data，表示新增子类
  }
  dialogVisible.value = true;
};

// 弹窗提交处理
const handleDialogSubmit = async (data: WMS.Basic.ItemCategoryInfo) => {
  try {
    if (dialogType.value === "add") {
      await WmsItemCategoryService.createItemCategory(data);
      ElMessage.success("新增分类成功");
    } else {
      await WmsItemCategoryService.updateItemCategory(data.id, data);
      ElMessage.success("更新分类成功");
    }
    dialogVisible.value = false;
    refreshData();
  } catch (error) {
    ElMessage.error(`${dialogType.value === "add" ? "新增" : "更新"}分类失败`);
    console.error("Error submitting category:", error);
  }
};

// 删除处理
const handleDelete = async (row: WMS.Basic.ItemCategoryInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${row.categoryName}" 吗？`,
      "删除确认",
      {
        type: "warning",
      },
    );

    await WmsItemCategoryService.deleteItemCategory(row.id);
    ElMessage.success("删除分类成功");
    refreshData();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除分类失败");
      console.error("Error deleting category:", error);
    }
  }
};

// 页面初始化
onMounted(() => {
  fetchTreeData();
});
</script>

<style lang="scss" scoped>
.wms-item-category-page {
  .art-table-card {
    :deep(.el-card__body) {
      padding: 16px;
    }
  }
}
</style>
